//
//  FQDUserSettingViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 9/9/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import <MobileCoreServices/MobileCoreServices.h>
#import "FQDUserSettingViewController.h"
#import "FQDEditShortSettingViewController.h"
#import "FQDEditLongSettingViewController.h"
#import "FQDChangePassViewController.h"
#import "FQDSettingOption.h"
#import "FQDNavigationView.h"
#import "FQDPlainSettingCell.h"
#import "FQDSwitchSettingCell.h"
#import "FQDCenterSettingCell.h"
#import "FQDAccountManager.h"
#import "FQDRestModel.h"

#import "Masonry.h"
#import "UIButton+WebCache.h"

@interface FQDUserSettingViewController () <UITableViewDelegate,
                                            UITableViewDataSource,
                                            UINavigationControllerDelegate,
                                            UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIButton *avatarButton;
@property (nonatomic, strong) UILabel *editAvatarLabel;
@property (nonatomic, strong) UITableView *settingTableView;
@property (nonatomic, strong) NSArray *optionList;
@property (nonatomic, strong) NSArray *sectionTitles;

@end

@implementation FQDUserSettingViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupOptions];
    [self setupNavigationView];
    [self setupTableView];
    [self setupNotifications];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupOptions
{
    FQDUser *user = [[FQDAccountManager sharedManager] currentUser];
    
    // Section 0
    FQDSettingOption *nameOption = [FQDSettingOption optionWithTitle:@"姓名"];
    nameOption.detail = user.username;
    nameOption.cellClass = [FQDPlainSettingCell class];
    [nameOption setSelectionBlock:^{
        FQDEditShortSettingViewController *essVC = [[FQDEditShortSettingViewController alloc] init];
        essVC.blurBgImage = self.blurBgImage;
        essVC.settingType = QDailyPersonalInfoTypeUsername;
        essVC.currentSettingValue = user.username;
        [self.navigationController pushViewController:essVC animated:YES];
    }];
    
    FQDSettingOption *briefOption = [FQDSettingOption optionWithTitle:@"简介"];
    briefOption.detail = user.signature;
    briefOption.cellClass = [FQDPlainSettingCell class];
    
    NSArray *section0 = @[ nameOption, briefOption ];
    NSString *nameForSection0 = @"个人信息";
   
    // Section 1
    FQDSettingOption *mailOption = [FQDSettingOption optionWithTitle:@"邮箱"];
    mailOption.detail = user.email;
    mailOption.cellClass = [FQDPlainSettingCell class];
    [mailOption setSelectionBlock:^{
        FQDEditShortSettingViewController *essVC = [[FQDEditShortSettingViewController alloc] init];
        essVC.blurBgImage = self.blurBgImage;
        essVC.settingType = QDailyPersonalInfoTypeEmail;
        essVC.currentSettingValue = user.email;
        essVC.title = @"邮箱";
        [self.navigationController pushViewController:essVC animated:YES];
    }];
    
    FQDSettingOption *addressOption = [FQDSettingOption optionWithTitle:@"地址"];
    addressOption.detail = user.address;
    addressOption.cellClass = [FQDPlainSettingCell class];
    [addressOption setSelectionBlock:^{
        FQDEditLongSettingViewController *elsVC = [[FQDEditLongSettingViewController alloc] init];
        elsVC.blurBgImage = self.blurBgImage;
        elsVC.settingType = QDailyPersonalInfoTypeAddress;
        elsVC.currentSettingValue = user.address;
        elsVC.title = @"地址";
        [self.navigationController pushViewController:elsVC animated:YES];
    }];
    
    FQDSettingOption *phoneOption = [FQDSettingOption optionWithTitle:@"手机"];
    phoneOption.detail = user.phone;
    phoneOption.cellClass = [FQDPlainSettingCell class];
    phoneOption.hasMore = NO;
    
    NSArray *section1 = @[ mailOption, addressOption, phoneOption];
    NSString *nameForSection1 = @"联系方式";
    
    // Section 2
    FQDSettingOption *wechatOption = [FQDSettingOption optionWithTitle:@"微信"];
    wechatOption.cellClass = [FQDSwitchSettingCell class];
    wechatOption.icon = @"wechat-1";
    wechatOption.value = @(user.connectedToWechat);
    
    FQDSettingOption *weiboOption = [FQDSettingOption optionWithTitle:@"新浪微博"];
    weiboOption.cellClass = [FQDSwitchSettingCell class];
    weiboOption.icon = @"weibo-1";
    weiboOption.value = @(user.connectedToWeibo);
    
    FQDSettingOption *qqOption = [FQDSettingOption optionWithTitle:@"QQ"];
    qqOption.cellClass = [FQDSwitchSettingCell class];
    qqOption.icon = @"QQ-1";
    qqOption.value = @(user.connectedToQQ);
    
    NSArray *section2 = @[ wechatOption, weiboOption, qqOption ];
    NSString *nameForSection2 = @"绑定社交账号";
    
    // Section 3
    FQDSettingOption *modifyPassOption = [FQDSettingOption optionWithTitle:@"修改密码"];
    modifyPassOption.cellClass = [FQDPlainSettingCell class];
    [modifyPassOption setSelectionBlock:^{
        FQDChangePassViewController *cpVC = [[FQDChangePassViewController alloc] init];
        cpVC.blurBgImage = self.blurBgImage;
        [self.navigationController pushViewController:cpVC animated:YES];
    }];
    
    NSArray *section3 = @[modifyPassOption];
    
    // Section 4
    FQDSettingOption *logoutOption = [FQDSettingOption optionWithTitle:@"登出"];
    logoutOption.cellClass = [FQDCenterSettingCell class];
    [logoutOption setSelectionBlock:^{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定退出当前登录么？" message:nil
                                              preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
          handler:^(UIAlertAction * _Nonnull action) {
            [self logout];
        }];
        
        [alertController addAction:cancel];
        [alertController addAction:confirm];
        [self presentViewController:alertController animated:YES completion:nil];
    }];

    NSArray *section4 = @[logoutOption];

    self.optionList = @[section0, section1, section2, section3, section4];
    self.sectionTitles = @[nameForSection0, nameForSection1, nameForSection2];
}

- (void)setupNavigationView
{
    self.navView.titleLabel.text = @"账号设置";
}

- (void)setupTableView
{
    CGSize viewSize = self.view.bounds.size;
    CGSize navSize = self.navView.frame.size;
    CGRect tableViewRect = CGRectMake(0, navSize.height, viewSize.width, viewSize.height - navSize.height);
    self.settingTableView = [[UITableView alloc] initWithFrame:tableViewRect style:UITableViewStyleGrouped];
    self.settingTableView.backgroundColor = [UIColor clearColor];
    self.settingTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    self.settingTableView.delegate = self;
    self.settingTableView.dataSource = self;
    [self.view addSubview:self.settingTableView];
    
    self.settingTableView.rowHeight = UITableViewAutomaticDimension;
    self.settingTableView.estimatedRowHeight = 45.0f;
   
    [self.settingTableView registerClass:[FQDPlainSettingCell class]
                  forCellReuseIdentifier:[FQDPlainSettingCell reuseId]];
    [self.settingTableView registerClass:[FQDSwitchSettingCell class]
                  forCellReuseIdentifier:[FQDSwitchSettingCell reuseId]];
    [self.settingTableView registerClass:[FQDCenterSettingCell class]
                  forCellReuseIdentifier:[FQDCenterSettingCell reuseId]];
    [self setupTableHeader];
}

- (void)setupTableHeader
{
    
    CGRect headerFrame = CGRectMake(0, 0, self.settingTableView.frame.size.width, 110.0f);
    UIView *header = [[UIView alloc] initWithFrame:headerFrame];
    header.backgroundColor = [UIColor clearColor];
    self.settingTableView.tableHeaderView = header;
    
    self.avatarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.avatarButton.layer.cornerRadius = 25.0f;
    self.avatarButton.layer.masksToBounds = YES;
    [self.avatarButton addTarget:self action:@selector(editAvatar:) forControlEvents:UIControlEventTouchUpInside];
    [header addSubview:self.avatarButton];
    
    self.editAvatarLabel = [[UILabel alloc] init];
    self.editAvatarLabel.font = FQDRegularFontWithSize(14.0f);
    self.editAvatarLabel.textColor = RGB(179, 179, 179);
    self.editAvatarLabel.text = @"编辑头像";
    [header addSubview:self.editAvatarLabel];
    
    [self updateAvatar];
    
    [self.avatarButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(header).offset(20);
        make.centerX.equalTo(header);
        make.size.equalTo(@50);
    }];
    
    WeakSelf;
    [self.editAvatarLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.avatarButton.mas_bottom).offset(7);
        make.left.equalTo(weakSelf.avatarButton);
    }];
}

- (void)updateAvatar
{
    FQDUser *user = [[FQDAccountManager sharedManager] currentUser];
    NSURL *avatarURL = [NSURL URLWithString:user.avatarURLString];
    [self.avatarButton sd_setImageWithURL:avatarURL forState:UIControlStateNormal];
}

- (void)setupNotifications
{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(userInfoDidChange:)
                          name:FQDAccountUserInfoDidChangeNotification object:nil];
}

- (void)logout
{
    [[FQDAccountManager sharedManager] logout:^(BOOL success) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

#pragma mark - Notifications
- (void)userInfoDidChange:(NSNotification *)note
{
    [self setupOptions];
    [self updateAvatar];
    [self.settingTableView reloadData];
}

#pragma mark - Event response
- (void)editAvatar:(id)sender
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil
                                          preferredStyle:UIAlertControllerStyleActionSheet];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIAlertAction *photoLibrary = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault
                                       handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePicker.delegate = self;
            [self presentViewController:imagePicker animated:YES completion:nil];
        }];

        [alertController addAction:photoLibrary];
    } else if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePicker.delegate = self;
            [self presentViewController:imagePicker animated:YES completion:nil];
        }];

        [alertController addAction:camera];
    }

    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancel];

    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDeleagate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    UIImage *image = info[UIImagePickerControllerEditedImage];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage] && (image != nil)) {
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0f);
        [self.avatarButton setImage:image forState:UIControlStateNormal];
        
        FQDMultipartFileData *partFileData = [FQDMultipartFileData fileDataWithData:imageData];
        partFileData.fileName = @"avatar.jpg";
        partFileData.mimeType = @"image/jpeg";
        
        [[QDailyAPI sharedAPI] updateAvatarWithPartFileData:partFileData
         completion:^(id responseObject, NSError *error) {
            NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
            if ([status integerValue] == 200) {
                id response = responseObject[@"response"];
                FQDUser *user = [FQDUser yy_modelWithJSON:response];
                [[FQDAccountManager sharedManager] changeCurrentUser:user];
            }
        }];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.optionList count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.optionList[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FQDSettingOption *option = self.optionList[indexPath.section][indexPath.row];
    Class cellClass = option.cellClass;
    UITableViewCell<FQDSettingCellProtocol> *cell =
    [tableView dequeueReusableCellWithIdentifier:[cellClass reuseId] forIndexPath:indexPath];
    cell.option = option;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FQDSettingOption *option = self.optionList[indexPath.section][indexPath.row];
    if (option.selectionBlock) {
        option.selectionBlock();
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section >= [self.sectionTitles count]) {
        return nil;
    }
    
    return self.sectionTitles[section];
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    header.textLabel.font = FQDRegularFontWithSize(14.0f);
    header.textLabel.textColor = RGB(179, 179, 179);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section >= [self.sectionTitles count]) {
        return 0;
    }
    
    return 40.0f;
}

@end
